package cn.wolfcode.wolf2w;

import cn.wolfcode.wolf2w.intercetor.LoginInterceptor;
import cn.wolfcode.wolf2w.resolver.UserInfoArgumentResolver;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Import;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.List;

@SpringBootApplication
public class App {

    @Bean
    // 把拦截器对象交给spring容器管理
    public LoginInterceptor loginInterceptor(){
        return new LoginInterceptor();
    }

    @Bean
    // 登录用户解析器
    public UserInfoArgumentResolver userInfoArgumentResolver(){ return new UserInfoArgumentResolver(); }

    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurer() {


            @Override
            public void addArgumentResolvers(List<HandlerMethodArgumentResolver> resolvers) {
                resolvers.add(userInfoArgumentResolver());
            }

            @Override
            // 配置拦截器
            public void addInterceptors(InterceptorRegistry registry) {
                registry.addInterceptor(loginInterceptor())
                        .addPathPatterns("/**") //要拦截的路径
                        .excludePathPatterns("/users/login")    //排除拦截的路径
                        .excludePathPatterns("/users/regist")
                        .excludePathPatterns("/users/sendVerifyCode")
                        .excludePathPatterns("/users/checkPhone")
                        .excludePathPatterns("/spots/query");
            }


            @Override
            //重写父类提供的跨域请求处理的接口
            public void addCorsMappings(CorsRegistry registry) {
                //添加映射路径
                registry.addMapping("/**")
                        //放行哪些原始域
                        .allowedOrigins("*")
                        //是否发送Cookie信息
                        .allowCredentials(true)
                        //放行哪些原始域(请求方式)
                        .allowedMethods("GET", "POST", "PUT", "DELETE","OPTIONS")
                        //放行哪些原始域(头部信息)
                        .allowedHeaders("*")
                        //暴露哪些头部信息（因为跨域访问默认不能获取全部头部信息）
                        .exposedHeaders("Header1", "Header2");
            }
        };
    }


    public static void main(String[] args) {
        SpringApplication.run(App.class,args);
    }

}
